package com.vcs.frm.web;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.vcs.frm.domain.Address;
import com.vcs.frm.domain.City;
import com.vcs.frm.domain.Jobseeker;
import com.vcs.frm.domain.Resume;
import com.vcs.frm.service.JobseekerService;
import com.vcs.frm.utils.Constants;
import com.vcs.frm.web.form.js.JobseekerRegFormBean;

@Controller
@RequestMapping(value = "/js")
public class JobseekerController {

	private final Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private JobseekerService jobseekerService;

	public void setJobseekerService(JobseekerService jobseekerService) {
		this.jobseekerService = jobseekerService;
	}

	/**
	 * Prepares Jobseeker's Registration Form
	 * 
	 * @return
	 */

	@RequestMapping(value = "/reg", method = RequestMethod.GET)
	public ModelAndView initJobseekerRegForm() {

		ModelAndView mav = new ModelAndView();

		log.info("method - initJobseekerRegForm");

		// current location list
		List<City> currentLocationList = new ArrayList<City>();
		currentLocationList.add(new City(1L, "Mumbai"));
		currentLocationList.add(new City(2L, "Noida"));
		mav.addObject("currentLocationList", currentLocationList);

		JobseekerRegFormBean formBean = new JobseekerRegFormBean();
		mav.addObject("jobseekerRegForm", formBean);
		mav.setViewName("reg");
		return mav;
	}

	/**
	 * Processes Jobseeker's Registration Form
	 * 
	 * @param jobseekerRegForm
	 * @param bindingResult
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/reg", method = RequestMethod.POST)
	public ModelAndView processJobseekerRegForm(
			@ModelAttribute("jobseekerRegForm") @Valid JobseekerRegFormBean jobseekerRegForm,
			BindingResult bindingResult,
			@RequestParam(value = "resumeFile", required = false) MultipartFile resumeFile,
			Model model, HttpSession session) {

		log.info("method - processJobseekerRegForm");

		ModelAndView mav = new ModelAndView();

		log.info("resumeFile : " + resumeFile.getContentType());

		/* Validation for resume file */
		log.info("before if : " + !resumeFile.isEmpty());
		if ((!resumeFile.isEmpty())
				&& (!resumeFile.getContentType().equals(
						Constants.WORD_2007_FILE))) {
			log.info("inside if : " + !resumeFile.isEmpty());
			bindingResult.addError(new FieldError("jobseekerRegForm",
					"resumeFile", "Only Word File accepted."));
		}

		mav.addObject("jobseekerRegForm", jobseekerRegForm);

		if (bindingResult.hasErrors()) {
			mav.setViewName("reg");
			return mav;
		} else {
			mav.setViewName("home");
		}

		Jobseeker jobseeker = new Jobseeker();
		jobseeker.setFirstName(jobseekerRegForm.getFirstName());
		jobseeker.setLastName(jobseekerRegForm.getLastName());
		jobseeker.setAge(jobseekerRegForm.getAge());
		jobseeker.setEmail(jobseekerRegForm.getEmail());
		jobseeker.setPhoneNumber(jobseekerRegForm.getPhoneNumber());

		if (resumeFile != null) {
			try {
				log.info("---> " + resumeFile.getBytes().length);
				Resume res = new Resume();
				res.setResumeFileName(resumeFile.getName());
				res.setResumeFile(resumeFile.getBytes());
				jobseeker.setResume(res);
			} catch (IOException e1) {
				log.info(e1);
			}
		}
		
		/* format string to date */
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

		try {
			jobseeker.setBirthDate(df.parse(jobseekerRegForm.getBirthDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// current location
		City city = new City();
		city.setCityId(new Long(jobseekerRegForm.getCurrentLocation()));
		jobseeker.setCurrentLocation(city);

		// address
		Address a = new Address();
		a.setLineOne(jobseekerRegForm.getLineOne());
		a.setLineTwo(jobseekerRegForm.getLineTwo());
		a.setLineThree(jobseekerRegForm.getLineThree());
		// TODO: SET CITY AND STATE
		jobseeker.setAddress(a);

		jobseekerService.saveJobseeker(jobseeker, jobseekerRegForm
				.getPassword());

		System.out.println(jobseekerRegForm.getBirthDate());
		return mav;
	}

	@RequestMapping(value = "/{profileId}")
	public ModelAndView getJobseekerProfileById(
			@PathVariable("profileId") Long profileId) {
		log.info("profile id : " + profileId);
		ModelAndView mav = new ModelAndView();

		mav.setViewName("jsProfile");
		return mav;
	}

	@RequestMapping(value = "/profile")
	public ModelAndView getJobseekerProfileFromSession(
			HttpServletRequest request) {
		log.info("method - getJobseekerProfileFromSession");
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		mav.addObject("js", session.getAttribute("jobseeker"));
		mav.setViewName("jsProfile");
		return mav;
	}

}
